<template>
  <div>
    <!-- 头部搜索 -->
    <header class="home-header wrap" :class="{'active' : state.headerScroll}">
      <router-link tag="i" to="./city">{{location.cityName || '未定位'}}<i class="iconfont icon-search"></i></router-link>
      <div class="header-search" @click="toProductList">
        <i class="iconfont icon-search"></i>
        <span class="search-title">搜索商品名称</span>
      </div>
      <router-link class="login" tag="span" to="./user">
        <van-icon name="manager-o" />
      </router-link>
    </header>
    <NavBar />
    <!-- 轮播图 -->
    <Swiper :list="state.swiperList"></Swiper>
    <!-- 功能区 -->
    <div class="category-list">
      <div v-for="item in state.categoryList" :key="item.categoryId" @click="jumpToCategory(item)">
        <img :src="item.imgUrl">
        <span>{{item.name}}</span>
      </div>
    </div>
    <!-- 品牌区 -->
    <div class="brand">
      <header class="brand-header">精选品牌</header>
      <van-skeleton title :row="1" :loading="loading">
        <div class="brand-box">
          <div class="brand-item" v-for="item in brandList" :key="item.id" @click="goToBrand(item)">
            <img :src="item.imagePath" loading="lazy" alt="">
            <div class="brand-desc">
              <div class="title">{{ item.name }}</div>
            </div>
          </div>
        </div>
      </van-skeleton>
    </div>
    <!-- 商品区 -->
    <div class="good">
      <header class="good-header">热门商品</header>
      <van-skeleton title :row="3" :loading="loading">
        <div class="good-box">
          <div class="good-item" v-for="item in recommends" :key="item.id" @click="goToDetail(item)">
            <img :src="item.imagePath" alt="">
            <div class="good-desc">
              <div class="title">{{ item.title }}</div>
              <div class="brand">{{item.brand_id}}</div>
              <div class="price">¥ {{ item.price }}</div>
            </div>
          </div>
        </div>
      </van-skeleton>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import Swiper from '@/components/Swiper.vue'
import NavBar from '@/components/NavBar.vue'
import { fetchBrandList } from '@/service/brand'
import { getLocal } from '@/common/js/utils'
import {
  showLoadingToast,
  closeToast,
  Skeleton as VanSkeleton,
  Icon as VanIcon
} from 'vant'
import { useCartStore } from '@/stores/cart'
import { useLocation } from "@/stores/location"
import { ref } from 'vue'
import {fetchGoodList} from "@/service/good";
import {useBrandStoreHook} from "@/stores/brand";

const cart = useCartStore()
const router = useRouter()
//#region 加载状态
const loading = ref(true)
//#endregion
//#region 品牌列表
const uniqueList = (list: any[], key: string) => {
  const newList: any[] = []
  const map: any = {}
  for (let index = 0; index < list.length; index++) {
    const element = list[index]
    if(map[element[key]]) continue
    map[element[key]] = true
    newList.push(element)
  }
  return newList
}

const brandList = ref<any[]>([])
const getBrandList = async () => {
  const res = await fetchBrandList(location.cityCode)
  brandList.value = uniqueList(res.data, 'id')
}
//#endregion
//#region 推荐商品
const recommends = ref<any[]>([])
const getGoods = async () => {
  const res = await fetchGoodList()
  recommends.value = res.data.list
}
//#endregion
type stateType = {
  swiperList: any[]
  isLogin: boolean
  headerScroll: boolean
  brandList: any[]
  hots: any[]
  newGoodses: any[]
  recommends: any[]
  categoryList: any[]
  loading: boolean
}
const state = reactive<stateType>({
  swiperList: [],
  isLogin: false,
  headerScroll: false,
  brandList: [],
  hots: [],
  newGoodses: [],
  recommends: [],
  categoryList: [
    {
      name: '蛋糕甜品',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230724163921_426.png',
      categoryId: 34
    },
    {
      name: '休闲零食',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230724164322_13.png',
      categoryId: 45
    },
    {
      name: '粮食副食',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230724164616_369.png',
      categoryId: 54
    },
    {
      name: '生鲜食品',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230724165446_8.png',
      categoryId: 61
    },
    {
      name: '甄选鲜花',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230724165601_819.png',
      categoryId: 66
    },
    {
      name: '烘焙周边',
      imgUrl: 'https://image-oss.dangaoss.cn/cats/cats_20230726172545_327.png',
      categoryId: 76
    },
    {
      name: '我的订单',
      imgUrl: 'https://image-oss.dangaoss.cn/home_page/home_page_20250523101506_996.png',
      categoryId: 100001
    },
    {
      name: '我的',
      imgUrl: 'https://www.dangaoss.com/h5/v2/css/img/vip/home_icon.gif',
      categoryId: 100002
    }
  ],
  loading: true
})

const { location, getCity } = useLocation()
onMounted(async () => {
  const token = getLocal('token')
  if (token) {
    state.isLogin = true
    cart.updateCart()
  }
  if(!location.cityName) await getCity()

  showLoadingToast({
    message: '加载中...',
    forbidClick: true
  })

  state.swiperList = [
    // {
    //   carouselUrl: 'https://image-oss.dangaoss.cn/home_page/home_page_20250114151723_259.jpg',
    //   redirectUrl: '',
    // },
    // {
    //   carouselUrl: 'https://image-oss.dangaoss.cn/home_page/home_page_20250210113711_735.jpg',
    //   redirectUrl: '',
    // },
    // {
    //   carouselUrl: 'https://image-oss.dangaoss.cn/home_page/home_page_20250220115627_697.jpg',
    //   redirectUrl: '',
    // },
    // {
    //   carouselUrl: 'https://image-oss.dangaoss.cn/home_page/home_page_20250220135223_16.jpg',
    //   redirectUrl: '',
    // }
    {
      carouselUrl: '/banner.jpg',
      redirectUrl: '',
    }
  ]

  await getBrandList()
  await getGoods()
  loading.value = false
  closeToast()
})

const toProductList = () => {
  router.push({
    path: 'product-list'
  })
}

const brandStore = useBrandStoreHook()
const goToBrand = (item: any) => {
  brandStore.setBrand(item)
  router.push({
    path: 'brand',
  })
}

nextTick(() => {
  document.body.addEventListener('scroll', () => {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    state.headerScroll = scrollTop > 100
  })
})
const goToDetail = (item) => {
  router.push({ path: `/product`, query: { id: item.id } })
}

const jumpToCategory = (item) => {
  if(item.categoryId === 100001) {
    router.push({ path: `/order`})
    return
  }
  if(item.categoryId === 100002) {
    router.push({ path: `/user`})
    return
  }
  router.push({
    path: `/category`,
    query: {
      categoryId: item.categoryId,
    }
  })
}
</script>

<style lang="less" scoped >
  @import '../common/style/mixin';
  .home-header {
      position: fixed;
      left: 0;
      top: 0;
      .wh(100%, 50px);
      .fj();
      line-height: 50px;
      padding: 0 15px;
      .boxSizing();
      font-size: 15px;
      color: #fff;
      z-index: 10000;
      .nbmenu2 {
        color: @primary;
      }
      &.active {
        background: @primary;
        .nbmenu2 {
          color: #fff;
        }
        .login {
          color: #fff;
        }
      }

      .header-search {
          display: flex;
          width: 74%;
          line-height: 20px;
          margin: 10px 0;
          padding: 5px 0;
          color: #232326;
          background: rgba(255, 255, 255, .7);
          border-radius: 20px;
          .app-name {
              padding: 0 10px;
              color: @primary;
              font-size: 20px;
              font-weight: bold;
              border-right: 1px solid #666;
          }
          .icon-search {
              padding: 0 10px;
              font-size: 17px;
          }
          .search-title {
              font-size: 12px;
              color: #666;
              line-height: 21px;
          }
      }
      .icon-iconyonghu{
        color: #fff;
        font-size: 22px;
      }
      .login {
        color: @primary;
        line-height: 52px;
        .van-icon-manager-o {
          font-size: 20px;
          vertical-align: -3px;
        }
      }
  }
  .category-list {
    display: flex;
    flex-shrink: 0;
    flex-wrap: wrap;
    width: 94vw;
    border-radius: 20px;
    background: #fff;
    margin: 0 auto;
    margin-top: -60px;
    padding-bottom: 13px;
    div {
      display: flex;
      flex-direction: column;
      width: 25%;
      text-align: center;
      img {
        .wh(40px, 40px);
        margin: 13px auto 4px auto;
      }
    }
  }
  .brand {
    .brand-header {
      background: #f9f9f9;
      height: 50px;
      line-height: 50px;
      text-align: center;
      color: @primary;
      font-size: 16px;
      font-weight: 500;
    }
    .brand-box {
      display: flex;
      overflow: auto;
      padding: 16px;
      .brand-item {
        margin-right: 10px;
        width: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        img {
          display: block;
          width: 60px;
          height: 60px;
          margin: 0 auto;
          border-radius: 0.2rem;
          border: 1.5px solid #dddddd;
        }
        .brand-desc {
          width: 100%;
          text-align: center;
          font-size: 14px;
          padding-top: 10px;
          .title {
            width: 65px;
            white-space: nowrap;
            color: #222333;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
  .good {
    padding-bottom: 64px;
    .good-header {
      background: #f9f9f9;
      height: 50px;
      line-height: 50px;
      text-align: center;
      color: @primary;
      font-size: 16px;
      font-weight: 500;
    }
    .good-box {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      .good-item {
        box-sizing: border-box;
        width: 50%;
        border-bottom: 1PX solid #e9e9e9;
        padding: 10px 10px;
        img {
          display: block;
          width: 120px;
          height: 120px;
          border-radius: 12px;
          margin: 0 auto;
        }
        .good-desc {
          text-align: center;
          font-size: 14px;
          padding: 10px 0;
          .title {
            color: #222333;
          }
          .price {
            color: @primary;
          }
        }
        &:nth-child(2n + 1) {
          border-right: 1PX solid #e9e9e9;
        }
      }
    }
  }
  .floor-list {
      width: 100%;
      padding-bottom: 50px;
      .floor-head {
        width: 100%;
        height: 40px;
        background: #F6F6F6;
      }
      .floor-content {
        display: flex;
        flex-shrink: 0;
        flex-wrap: wrap;
        width: 100%;
        .boxSizing();
        .floor-category {
          width: 50%;
          padding: 10px;
          border-right: 1px solid #dcdcdc;
          border-bottom: 1px solid #dcdcdc;
          .boxSizing();
          &:nth-child(2n) {
            border-right: none;
          }
          p {
            font-size: 17px;
            color: #333;
            &:nth-child(2) {
              padding: 5px 0;
              font-size: 13px;
              color: @primary;
            }
          }
          .floor-products {
            .fj();
            width: 100%;
            img {
              .wh(65px, 65px);
            }
          }
      }
    }
  }
</style>